package com.shinobi.timetracker.database;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.steema.teechart.DateTime;

//import com.steema.teechart.DateTime;

/**
 * Created by IntelliJ IDEA. User: Semy Date: 10.05.11 Time: 21:27 To change
 * this template use File | Settings | File Templates.
 */
public class TimeResultProvider {

	private static final String TAG = "TimeResultProvider";

	public static TimerResult[] GetAllTimeResults(Context ctx) throws Exception {

		DatabaseHelper dbHelper = new DatabaseHelper(ctx);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		try {

			String[] s = {};
			Cursor result = db.rawQuery(
					"SELECT * FROM time t JOIN tag ta ON t.tag_id == ta.id", s);

			ArrayList<TimerResult> timerResults = new ArrayList<TimerResult>();

			if (result.getCount() == 0) {
				return (TimerResult[]) timerResults.toArray();
			} else {

				result.moveToFirst();
				TimerResult timerResult = new TimerResult(result.getString(5));
				long startTime = Long.parseLong(result.getString(2));
				long endTime = Long.parseLong(result.getString(3));

				timerResult.setStartTime(startTime);
				timerResult.setStopTime(endTime);

				timerResults.add(timerResult);

				while (result.moveToNext()) {

					timerResult = new TimerResult(result.getString(5));
					startTime = Long.parseLong(result.getString(2));
					endTime = Long.parseLong(result.getString(3));

					timerResult.setStartTime(startTime);
					timerResult.setStopTime(endTime);

					timerResults.add(timerResult);
				}

				return (TimerResult[]) timerResults
						.toArray(new TimerResult[timerResults.size()]);
			}

		} catch (Exception exc) {

			throw exc;
		} finally {

			db.close();
			dbHelper.close();
		}
	}

	public static void AddTimerResult(Context ctx, TimerResult result)
			throws Exception {

		DatabaseHelper dbHelper = new DatabaseHelper(ctx);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		Tag tag = TagsProvider.GetTag(ctx, result.getTag());

		if (tag != null) {

			ContentValues newValues = new ContentValues(1);
			newValues.put(DatabaseHelper.KEY_STARTTIME,
					String.valueOf(result.getStartTime()));
			newValues.put(DatabaseHelper.KEY_STOPTIME,
					String.valueOf(result.getStopTime()));
			newValues.put(DatabaseHelper.KEY_TAG_ID, tag.getId());

			if (db.insert("time", "id", newValues) != 1) {
				Log.d(TAG, "Added timerResult");
			} else {
				Log.e(TAG, "Error dodawania timerResult");
			}
		}
		db.close();
		dbHelper.close();
	}

	public static HashMap<DateTime, Long> GetResults(Context ctx,
			DateTime start, DateTime stop, String tag) {

		HashMap<DateTime, Long> results = new HashMap<DateTime, Long>();

		DatabaseHelper dbHelper = new DatabaseHelper(ctx);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		Tag t;
		try {
			t = TagsProvider.GetTag(ctx, tag);

			if (t == null) {
				return results;
			}

		} catch (Exception e) {
			return results;
		}

		String[] s = { String.valueOf(t.getId()),
				String.valueOf(start.getTimeInMillis()),
				String.valueOf(stop.getTimeInMillis()) };
		Cursor result = db
				.rawQuery(
						"SELECT * FROM time t WHERE t.tag_id == ? AND t.endtime > ? AND t.starttime < ?",
						s);

		ArrayList<TimerResult> timerResults = new ArrayList<TimerResult>();

		if (result.getCount() == 0) {
			return results;
		} else {
			result.moveToFirst();
			TimerResult timerResult = GetObject(result, t.getName());

			timerResults.add(timerResult);

			while (result.moveToNext()) {

				timerResult = GetObject(result, t.getName());
				timerResults.add(timerResult);
			}
		}

		for (TimerResult tr : timerResults) {
			Long mils = 0L;

			DateTime dtstart = new DateTime(tr.getStartTime());
			DateTime dtstop = new DateTime(tr.getStopTime());

			Date dstart = new Date(dtstart.getYear(), dtstart.getMonth(),
					dtstart.getDay());
			Date dstop = new Date(dtstop.getYear(), dtstop.getMonth(),
					dtstop.getDay());

			if (dtstart.getTimeInMillis() < start.getTimeInMillis()) {
				mils = tr.getStopTime() - dstop.getTime();

				DateTime dtDateTime = new DateTime(dstop.getTime());
				if (results.containsKey(dtDateTime)) {
					long r = results.get(dtDateTime) + mils;
					results.put(dtDateTime, r);
				} else {
					results.put(dtDateTime, mils);
				}

			} else if (dtstart.equals(dstop)) {
				mils = Long.parseLong(tr.getDiff());

				DateTime dtDateTime = new DateTime(dstart.getTime());
				if (results.containsKey(dtDateTime)) {
					long r = results.get(dtDateTime) + mils;
					results.put(dtDateTime, r);
				} else {
					results.put(dtDateTime, mils);
				}

			} else if (dstart.equals(dstop)) {

				mils = dstop.getTime() - dtstart.getTimeInMillis();

				DateTime dtDateTime = new DateTime(dstart.getTime());
				if (results.containsKey(dtDateTime)) {
					long r = results.get(dtDateTime) + mils;
					results.put(dtDateTime, r);
				} else {
					results.put(dtDateTime, mils);
				}

				mils = dtstop.getTimeInMillis() - dstop.getTime();

				dtDateTime = new DateTime(dstop.getTime());
				if (results.containsKey(dtDateTime)) {
					long r = results.get(dtDateTime) + mils;
					results.put(dtDateTime, r);
				} else {
					results.put(dtDateTime, mils);
				}
			} else if (dtstop.getTimeInMillis() > stop.getTimeInMillis()) {

				mils = dstop.getTime() - dtstart.getTimeInMillis();

				DateTime dtDateTime = new DateTime(dstart.getTime());
				if (results.containsKey(dtDateTime)) {
					long r = results.get(dtDateTime) + mils;
					results.put(dtDateTime, r);
				} else {
					results.put(dtDateTime, mils);
				}
			}
		}

		return results;
	}

	private static TimerResult GetObject(Cursor obj, String tag) {

		TimerResult timerResult = new TimerResult(tag);
		long startTime = Long.parseLong(obj.getString(1));
		long endTime = Long.parseLong(obj.getString(2));

		timerResult.setStartTime(startTime);
		timerResult.setStopTime(endTime);

		return timerResult;
	}
}
